<!--
 * @Author: Olivia
 * @Date: 2022-08-24 22:21:38
 * @custom_string_Olivia: Less is more
-->
<template>
 <div class="search-suggestion">
  <van-cell v-for="(item,index) in suggestions" :key="index" icon="search" @click="$emit('search',item)">
    <div slot="title" v-html="highlight(item)"></div>
  </van-cell>
 </div>
</template>
<script>
import { getSearchSuggestions } from '../../../api/search'
import { debounce } from 'lodash'
export default {
  name: 'searchSuggestion',
  data () {
    return {
      suggestions: []
    }
  },
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  watch: {
    searchText: {
      handler: debounce(function (value) {
        this.loadSearchSuggestions(value)
      }, 1000),
      //   handler (value) {
      //     this.loadSearchSuggestions(value)
      //   },
      immediate: true
    }
  },
  created () {
  },
  computed: {
  },
  methods: {
    async loadSearchSuggestions (q) {
      try {
        const { data } = await getSearchSuggestions(q)
        this.suggestions = data.data.options
        console.log(this.suggestions)
      } catch (error) {
        this.$toast(error)
      }
    },
    highlight (item) {
      const highlightStr = `<span class="active"> ${this.searchText} </span>`
      const reg = new RegExp(this.searchText, 'gi')
      return item.replace(reg, highlightStr)
    }
  }
}
</script>
<style lang='less'  scoped>
    .search-suggestion{
        /deep/ span.active{
            color:pink
        }
    }
</style>
